package com.jsu.springboot_crop.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.jsu.springboot_crop.dao.KnowledgeDao;
import com.jsu.springboot_crop.entity.Knowledge;
import com.jsu.springboot_crop.service.KnowledgeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.Date;
import java.util.List;

@Service
public class KnowledgeServiceImpl implements KnowledgeService {
    @Autowired
    KnowledgeDao knowledgeDao;

    Integer pageSize=30;
    @Override
    public PageInfo<Knowledge> findPage(Integer pageNum) {
        PageHelper.startPage(pageNum,pageSize);
        List<Knowledge> knowledge=knowledgeDao.selectAll();
        PageInfo<Knowledge> knowledgePageInfo=new PageInfo<>(knowledge);
        return knowledgePageInfo;
    }

    @Override
    public PageInfo<Knowledge> findPageByKeys(String keys, Integer pageNum) {
        PageHelper.startPage(pageNum,pageSize);
        List<Knowledge> knowledge=knowledgeDao.selectAllByKeys(keys);
        PageInfo<Knowledge> knowledgePageInfo=new PageInfo<>(knowledge);
        return knowledgePageInfo;
    }

    @Override
    public Knowledge selectById(Integer id) {
        Knowledge knowledge=knowledgeDao.selectByPrimaryKey(id);
        return knowledge;
    }

    @Override
    public List<Knowledge> selectByUsername(String name) {
        return knowledgeDao.selectByExample(name);
    }

    @Override
    public void add(Knowledge knowledge) {
        //获取登陆的用户名
        UserDetails principal = (UserDetails) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        String name = principal.getUsername();
        knowledge.setOwnName(name);
        knowledge.setCreateTime(new Date());
        knowledge.setUpdateTime(new Date());
        knowledgeDao.insertSelective(knowledge);
    }

    @Override
    public void update(Knowledge knowledge, Integer id) {
        //获取用户名
        UserDetails principal=(UserDetails) SecurityContextHolder.getContext().getAuthentication();
        String name=principal.getUsername();
        //设置参数
        knowledge.setCreateTime(new Date());
        knowledge.setUpdateTime(new Date());
        //调用方法
        knowledgeDao.updateByPrimaryKeySelective(knowledge);
    }

    @Override
    public void delete(Integer id) {
        knowledgeDao.deleteByPrimaryKey(id);
    }
}
